package com.tutu.common.util;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import com.tutu.user.entity.SysUser;

public class Constants {

	/**
	 * 返回访问客户端的IP
	 * @param request
	 * @return
	 */
	public static String getIPAddr(HttpServletRequest request){
		String tempIp = request.getHeader("x-forwarded-for");
		if(tempIp==null||tempIp.length()==0||"unknown".equalsIgnoreCase(tempIp)){
			tempIp = request.getHeader("Proxy-Client-IP");
		}
		if(tempIp==null||tempIp.length()==0||"unknown".equalsIgnoreCase(tempIp)){
			tempIp = request.getHeader("WL-Proxy-Client-IP");
		}
		if(tempIp==null||tempIp.length()==0||"unknown".equalsIgnoreCase(tempIp)){
			tempIp = request.getRemoteAddr();
		}
		return tempIp;
	}
	
	public static String getPrePage(HttpServletRequest request){
		if (StringUtils.isEmpty(request.getParameter("returnUrl"))) {
			return request.getHeader("Referer");
		}
		return request.getParameter("returnUrl");
	}
	
	public static boolean isAjaxRequest(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        if (header != null && "XMLHttpRequest".equals(header))
            return true;
        else
            return false;
    }
	
	/**
	 * 获取用户信息
	 * @return
	 */
	public static SysUser getCurrentUser(){
//		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if(null!=authentication){
			Object object = authentication.getPrincipal();
			if(object instanceof SysUser)
				return (SysUser) object;
		}
		return null;
	}
}
